//将网络图片转未 PixelMap，并绘制到image元素上
package com.kunminx.viabus.utils;

import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;
import com.zzrv5.mylibrary.ZZRResponse;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Image;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

/**
 * ImageNetWork get http img
 *
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class ImageNetWork {
    // private static final  HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0, "HmOSImageLoader");
    private  AbilitySlice abilitySlice;
    private  Image image;
    private  String url;

    public ImageNetWork(AbilitySlice mAbilitySlice, Image mImage, String mUrl) {
        this.abilitySlice = mAbilitySlice;
        this.image = mImage;
        this.url = mUrl;
    }

    /**
    * start
    */
    public  void start() {
        ZZRHttp.get(url, new ZZRCallBack.CallBackString() {
            @Override
            public void onFailure(int code, String errorMessage) {
                //http访问出错了，此部分内容在主线程中工作;
                //可以更新UI等操作,请不要执行阻塞操作。
            }
            @Override
            public String onParseResponse(ZZRResponse response) {
                //创建图片源
                ImageSource imageSource = ImageSource.create(response.inputStream, null);
                //根据图片源创建位图
                PixelMap pixelMap = imageSource.createPixelmap(null);
                //需要异步渲染UI
                abilitySlice.getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        //展示到组件上
                        image.setPixelMap(pixelMap);
                        pixelMap.release();

                    }
                });
                return super.onParseResponse(response);
            }
            @Override
            public void onResponse(String response) {

            }
        });
    }
}